package com.situ.manager.controller;

import com.situ.manager.mapper.AdminMapper;
import com.situ.manager.pojo.Admin;
import com.situ.manager.pojo.query.AdminQuery;
import com.situ.manager.service.AdminService;
import com.situ.manager.util.PageResult;
import com.situ.manager.util.Result;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    //注入过来使用
    //@Autowired
    //private AdminMapper adminMapper;
    @Autowired
    private AdminService adminService;

    // /admin/list
    /*@RequestMapping("/list")
    @ResponseBody
    public List<Admin> list() {
        //soutm
        System.out.println("AdminController.list");
        List<Admin> list = adminService.list();
        return list;
    }*/

    @RequestMapping("/list")
    @ResponseBody
    public PageResult list(AdminQuery adminQuery) {
        System.out.println("AdminController.list");
        PageResult pageResult = adminService.list(adminQuery);
        return pageResult;
    }

    //转发到界面，返回一个String
    @RequestMapping("/toAdminList")
    public String toAdminList() {
        return "admin_list";
    }

    @RequestMapping("/toAdminAdd")
    public String toAdminAdd() {
        return "admin_add";
    }

    // /admin/toLogin
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public Result login(String name, String password, HttpSession session) {
        Admin admin = adminService.login(name, password);
        if (admin == null) {//用户名或密码错误
            return Result.error("户名或密码错误");
        }

        //登录上之后把登录的凭证放到Session
        session.setAttribute("admin", admin);
        return Result.ok("登录成功");
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Result logout(HttpSession session) {
        //把登录的凭证移除掉
        session.removeAttribute("admin");
        return Result.ok("退出成功");
    }

    @RequestMapping("/deleteById")
    @ResponseBody
    public Result deleteById(Integer id) {
        //Alt+Enter
        adminService.deleteById(id);
        return Result.ok("删除成功");
    }

    @RequestMapping("/add")
    @ResponseBody
    public Result add(Admin admin) {
        adminService.add(admin);
        return Result.ok("添加成功");
    }

    @RequestMapping("/deleteAll")
    @ResponseBody
    public Result deleteAll(Integer[] ids) {
        //Alt+Enter
        adminService.deleteAll(ids);
        return Result.ok("删除成功");
    }
}
